

import UIKit
import SVProgressHUD


class YYOAuthViewController: UIViewController ,UIWebViewDelegate{

    let webView: UIWebView = UIWebView()

    override func loadView() {
        view = webView

        setupNav()
    }

    private func setupNav(){

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self , action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self , action: "autoFill")
        
        
    }



    @objc private func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in

        }
    }



    @objc private func autoFill(){


        // 代码里如何实现js注入
        let js = "document.getElementById(\"passwd\").value = \"xiaoziyong\";document.getElementById(\"userId\").value = \"xiaoziyong1008\""

        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }



    override func viewDidLoad() {
        super.viewDidLoad()


        //URLhttps://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=3879265751&redirect_uri=http://www.devshaw.com"
        //能够保证 URL 为非空 可以强制解包
        let url = NSURL(string: urlString)!

        let request = NSURLRequest(URL: url)

        webView.loadRequest(request)




        webView.delegate = self

    }






}


extension YYOAuthViewController{

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }


    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {

    }


    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if let absolueString = request.URL?.absoluteString{
            if absolueString.hasPrefix(OpenURL){


                if let query = request.URL?.query{
                    let code = query.substringFromIndex("code=".endIndex)
     print(code)

                    YYOauthViewModel().loadToken(code, sucess: { () -> () in
                     
                        self.dismiss()
                        }, failed: { () -> () in

                    })


                }
                return false
            }
        }
        return true
    }
}

